package com.sk.bilibili.service;

import com.sk.bilibili.property.CloudProperty;
import com.sk.bilibili.property.SmsProperty;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.sms.v20190711.SmsClient;
import com.tencentcloudapi.sms.v20190711.models.SendSmsRequest;
import com.tencentcloudapi.sms.v20190711.models.SendSmsResponse;
import lombok.SneakyThrows;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author 邵康
 * @date 2021/11/22 16:30
 */
@Service
public class SmsService implements InitializingBean {

    @Autowired
    private CloudProperty cloudProperty;
    @Autowired
    private SmsProperty smsProperty;
    private SmsClient smsClient;

    @Override
    public void afterPropertiesSet() throws Exception {
        Credential cred = new Credential(cloudProperty.getSecretId(),cloudProperty.getSecretKey());
        smsClient = new SmsClient(cred, cloudProperty.getRegion(), new ClientProfile());
    }

    @SneakyThrows
    public boolean sendMsg(String phone,String... param){
        SendSmsRequest req = buildRequest(phone,param);
        SendSmsResponse response = smsClient.SendSms(req);
        return response.getSendStatusSet()[0].getFee()>0;
    }

    private SendSmsRequest buildRequest(String phone, String[] param) {
        SendSmsRequest request = new SendSmsRequest();
        request.setPhoneNumberSet(new String[]{"+86"+phone});
        request.setSmsSdkAppid(smsProperty.getAppId());
        request.setSign(smsProperty.getSignName());
        request.setTemplateID(smsProperty.getTemplateId());
        request.setTemplateParamSet(param);
        return request;
    }

}
